package com.example.wyemail.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 获取链接工具类
 *
 * @author fxab
 * @date 2024/06/07
 */
public class DataUtil {
    private static final Pattern urlPattern = Pattern.compile("https://lab\\.alipay\\.com/user/activeUserValid\\.htm\\?ac[^\s]+");
    public static String findFolderWithPrefix(String directory, String prefix) throws IOException {
        try {
            return Files.list(Paths.get(directory))
                    .filter(Files::isDirectory)
                    .map(Path::getFileName)
                    .map(Path::toString)
                    .filter(name -> name.startsWith(prefix))
                    .findFirst()
                    .orElse(null);
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * 递归删除文件夹
     *
     * @param path 文件夹路径
     * @throws IOException ioexception
     */
    public static void deleteDirectory(Path path) throws IOException {
        if (Files.isDirectory(path)) {
            try (DirectoryStream<Path> entries = Files.newDirectoryStream(path)) {
                for (Path entry : entries) {
                    deleteDirectory(entry);
                }
            }
        }
        Files.delete(path);
    }

    /**
     * 获取数据
     */
    public static void getData(String mainDirectory, String accountDocument,String courseFile) throws InterruptedException {
        List<Map<String, String>> emailAccounts = new ArrayList<>();

        // 读取文件并解析内容
        System.out.println("Working Directory = " + System.getProperty("user.dir"));
        try (BufferedReader br = new BufferedReader(new FileReader(accountDocument))) {
            String line;
            while ((line = br.readLine()) != null) {
                String[] parts = line.split("\\s+");
                if (parts.length >= 3) {
                    Map<String, String> account = new HashMap<>();
                    account.put("email", parts[0]);
                    account.put("password", parts[1]);
                    account.put("phone", parts[2]);
                    emailAccounts.add(account);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        Map<String, List<Map<String, String>>> results = new LinkedHashMap<>();

        // 循环处理每个邮箱
        for (Map<String, String> account : emailAccounts) {
            String email = account.get("email");
            String password = account.get("password");
            String phone = account.get("phone");

            String emailPrefix = email.split("@")[0]; // 获取邮箱前缀部分（去掉@及其后面的部分）

            // 查找匹配的文件夹
            String matchedFolder;
            try {
                matchedFolder = findFolderWithPrefix(mainDirectory, emailPrefix);
            } catch (IOException e) {
                System.out.println("未找到匹配的文件夹: " + emailPrefix);
                continue;
            }

            if (matchedFolder == null) {
                System.out.println("未找到匹配的文件夹: " + emailPrefix);
                continue;
            }

            String dbPath = Paths.get(mainDirectory, matchedFolder, "search.db").toString();
            String sql = "SELECT * FROM Search_content";

            // 创建连接并查询数据库
            try (Connection con = DriverManager.getConnection("jdbc:sqlite:" + dbPath);
                 Statement stmt = con.createStatement();
                 ResultSet rs = stmt.executeQuery(sql)) {

                // 从最新的数据开始查找
                List<Map<String, String>> personAll = new ArrayList<>();
                while (rs.next()) {
                    Map<String, String> row = new HashMap<>();
                    row.put("last_data", rs.getString("c5"));
                    personAll.add(row);
                }

                boolean urlFound = false;
                for (int i = personAll.size() - 1; i >= 0; i--) {
                    String lastData = personAll.get(i).get("last_data");
                    Matcher matcher = urlPattern.matcher(lastData);
                    if (matcher.find()) {
                        String url = matcher.group(0);
                        // 截取到第一个空格的位置
                        int spaceIndex = url.indexOf('\n');
                        if (spaceIndex != -1) {
                            url = url.substring(0, spaceIndex);
                        }
                        if (!results.containsKey(phone)) {
                            results.put(phone, new ArrayList<>());
                        }
                        Map<String, String> resultAccount = new HashMap<>();
                        resultAccount.put("email", email);
                        resultAccount.put("password", password);
                        resultAccount.put("url", url);
                        System.out.println(url);
                        results.get(phone).add(resultAccount);
                        urlFound = true;
                        break; // 找到链接后跳出循环，继续下一个邮箱
                    }
                }
                if (!urlFound) {
                    System.out.println("未找到URL: " + email);
                }
            } catch (SQLException e) {
                System.out.println(email + "查询失败: " + e.getMessage());
            }
        }

        // 输出结果到文件
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(courseFile + "注册完成样本.txt"))) {
            for (Map.Entry<String, List<Map<String, String>>> entry : results.entrySet()) {
                String phone = entry.getKey();
                List<Map<String, String>> accounts = entry.getValue();
                for (Map<String, String> acc : accounts) {
                    writer.write(acc.get("email") + "----" + acc.get("password") + "----" + phone);
                    writer.newLine();
                }
                writer.newLine();
                for (Map<String, String> acc : accounts) {
                    writer.write(acc.get("url"));
                    writer.newLine();
                    writer.newLine();
                }
                writer.write("============================");
                writer.newLine();
                writer.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("输出已完成");

    }

    public static void deleteData(String mainDirectory, String accountDocument) throws InterruptedException {
        SoftInitUtil.Stop();
        Thread.sleep(2000);

        List<Map<String, String>> emailAccounts = new ArrayList<>();

        // 读取文件并解析内容
        System.out.println("Working Directory = " + System.getProperty("user.dir"));
        try (BufferedReader br = new BufferedReader(new FileReader(accountDocument))) {
            String line;
            while ((line = br.readLine()) != null) {
                String[] parts = line.split("\\s+");
                if (parts.length >= 3) {
                    Map<String, String> account = new HashMap<>();
                    account.put("email", parts[0]);
                    account.put("password", parts[1]);
                    account.put("phone", parts[2]);
                    emailAccounts.add(account);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        List<String> foldersToDelete = new ArrayList<>();

        // 循环处理每个邮箱
        for (Map<String, String> account : emailAccounts) {
            String email = account.get("email");
            String password = account.get("password");
            String phone = account.get("phone");

            String emailPrefix = email.split("@")[0]; // 获取邮箱前缀部分（去掉@及其后面的部分）

            // 查找匹配的文件夹
            String matchedFolder;
            try {
                matchedFolder = findFolderWithPrefix(mainDirectory, emailPrefix);
            } catch (IOException e) {
                System.out.println("未找到匹配的文件夹: " + emailPrefix);
                continue;
            }

            if (matchedFolder == null) {
                System.out.println("未找到匹配的文件夹: " + emailPrefix);
                continue;
            }
            foldersToDelete.add(Paths.get(mainDirectory, matchedFolder).toString());
        }


        // 删除文件夹
        for (String folder : foldersToDelete) {
            try {
                deleteDirectory(Paths.get(folder));
                System.out.println("Deleted folder: " + folder);
            } catch (IOException e) {
                System.out.println("Failed to delete folder: " + folder);
                e.printStackTrace();
            }
        }

        System.out.println("邮箱已批量删除");
    }
}

